package efrei.ngo.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;

import efrei.ngo.entity.ItemDetail;
import efrei.ngo.entity.User;
import efrei.ngo.util.DatabaseAccess;

/**
 * Servlet implementation class StorePostInDBServlet
 */
public class StorePostInDBServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StorePostInDBServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//titleName, description, context
		//User owner=(User)request.getAttribute("Owner");
		//ItemDetail tempItemDeail=new ItemDetail(null, request.getParameter("titleName") , request.getParameter("description"),
				//owner.getUsername(), request.getParameter("context"));
		System.out.println("Start Store Post In Database");
		String titleName=request.getParameter("titleName");
		String description=request.getParameter("description");
		String context=request.getParameter("context");
		int owner=((User)request.getSession().getAttribute("user")).getU_id();
		JSONObject jObResponse=new JSONObject();
		
		DatabaseAccess.connectToDB();
		try{
			if(DatabaseAccess.dbStorePostInDB(titleName,description,context,owner)){
				jObResponse.accumulate("result", true);
			} else {
				jObResponse.accumulate("result", false);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DatabaseAccess.endConnectionToDB();
		System.out.println(jObResponse.toString());
		response.getWriter().write(jObResponse.toString());
	}

}
